package com.huazai.apply.manager.service.impl;


import com.huazai.apply.manager.bean.User;
import com.huazai.apply.manager.dao.UserMapper;
import com.huazai.apply.manager.service.UserInitService;
import com.huazai.apply.manager.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.HashMap;
import java.util.Map;

/**
 * @author EZTTU
 */
public class UserInitServiceImpl implements UserInitService {

    private static final String MES_REGISTERED = "该用户ID已经注册过了";
    private static final String MES_RES_SUCCESS = "注册成功，快回去登录吧";
    private static final String MES_RES_FALL = "注册失败";
    private static final String MES_LOGIN_SUCCESS = "登录成功";
    private static final String MES_LOGIN_FALL = "登录失败，密码错误";
    private static final String MES_LOGIN_EXIST = "登录失败，用户不存在";

    @Override
    public String doRegister(User user) {
        String mes = null;

        Map<String, String> map = new HashMap<>();
        map.put("userId", user.getUserId());
        map.put("userField", user.getUserField());
        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            if (mapper.checkUser(map) != null) {
                mes = MES_REGISTERED;
            } else if (mapper.signUp(user)) {
                sqlSession.commit();
                mes = MES_RES_SUCCESS;
            } else {
                sqlSession.rollback();
                mes = MES_RES_FALL;
            }
            return mes;
        }
    }

    @Override
    public String doLogin(User user) {

        try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);

            String mes;
            Map<String, String> map = new HashMap<>();
            map.put("userId", user.getUserId());
            map.put("userField", user.getUserField());

            if (mapper.checkUser(map) == null) {
                mes = MES_LOGIN_EXIST;
                return mes;
            }
            map.put("userPassword", user.getUserPassword());
            if (mapper.checkUser(map) != null) {
                mes = MES_LOGIN_SUCCESS;
            } else {
                mes = MES_LOGIN_FALL;
            }
            return mes;
        }

    }
}
